﻿using System;
using System.Collections.Generic;
using System.Linq;
using UserSessionService.WebApi.Models;

namespace UserSessionService.WebApi.DataLayer
{
    public class InMemoryRepository : IUserSessionRepository
    {
        static List<UserSession> _userSessions = new List<UserSession>
        {
            new UserSession { UserId = "0" },
            new UserSession { UserId = "1", ViewedItems = { "foo", }},
            new UserSession { UserId = "2", ViewedItems = { "baa", "baa" }},
            new UserSession { UserId = "user1@hotmail.com", ViewedItems = { "111", "222", "333" }},
            new UserSession { UserId = "8", ViewedItems = { "do", "ray", "me", "fa", "so", "la", "tea", "doe" }},
        };
        
        public UserSession GetUserSession(string userId)
        {
            IEnumerable<UserSession> querySessions =
                from r in _userSessions
                where r.UserId == userId
                select r;

            return querySessions.FirstOrDefault();
        }

        public List<string> GetViewedItems(string userId, int count)
        {
            UserSession session = GetUserSession(userId);

            if (session != null)
                return session.ViewedItems.Take(count).ToList<string>();        
            else
                return null;
        }

        public void AddViewedItem(string userId, string productId)
        {
            var session = GetUserSession(userId);

            if (session != null)
                session.ViewedItems.Add(productId);
            else
                _userSessions.Add(
                    new UserSession
                    {
                        UserId = userId,
                        ViewedItems = new List<string> { productId }
                    });
        }

        public void DeleteViewedItems()
        {
            _userSessions.Clear();
        }
    }
}
